<html>
<head>
    <style>
    .node circle {
        fill: #fff;
        stroke: steelblue;
        stroke-width: 1.5px;
    }
    .node {
        font: 10px sans-serif;
    }
    .link {
        fill: none;
        stroke: #ccc;
        stroke-width: 1.5px;
    }
</style>
<script src="js/jsapi"></script>
<script>
    console.log('loading Google visualization');
    google.load('visualization', '1');
</script>
<script src="js/d3.v3.min.js"></script>
<script type="text/javascript">

var globalvar;

var orgChart = (function (google, d3) {

    var tree, diagonal, svg, root, m = [20, 120, 20, 120],
            w = 1280 - m[1] - m[3],
            h = 2000 - m[0] - m[2],
            i = 0;

    function init() {
        // Create and populate the data table.
        var query = new google.visualization.Query(
		'https://docs.google.com/a/ft.com/spreadsheet/ccc?key=0AuS2tvn8EoZydDNYWEJlRm1laXRmOW5sUF9INjBnSUE#gid=0&range=A1:C100');

        query.send(getData);
    }

    function getData(response) {
        if (response.isError()) {
            alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
            return;
        }

        var people = [],
                data = response.getDataTable(),
                length = data.getNumberOfRows(),
                row_index,
                hierarchy,
                complete_hierarchy;

		console.log(data);

        for (row_index = 0; row_index < length; row_index++) {
            people.push({
                name : data.getFormattedValue(row_index, 0),
                manager : data.getFormattedValue(row_index, 1),
                title : data.getFormattedValue(row_index, 2)
            });
        }
        //console.log(people);

        hierarchy = d3.nest()
                .key(function(d) { return d.manager; })
                .map(people);

        console.log(hierarchy);

	globalvar = hierarchy;

	console.log('Calling hierarchy from getData')
        
	complete_hierarchy = hierarchialise(hierarchy, hierarchy[''])[0];

        //console.log(complete_hierarchy);

        render(complete_hierarchy);
    }

    function hierarchialise(hierarchy, team) {
        var result = [],
                team_index;

        for(team_index = 0; team_index < team.length; team_index++) {
            var person = team[team_index];

            var manager = {
                name: person.name,
                title: person.title
            };

            if (typeof hierarchy[person.name] !== "undefined") {
				console.log('Calling hierarchy from hierarchalialise')
                manager['children'] = hierarchialise(hierarchy, hierarchy[person.name])
            }

            result.push(manager);
        }

        return result;
    }

    function render(hierarchy) {
        root = hierarchy;
        root.x0 = h / 2;
        root.y0 = 0;

        tree = d3.layout.tree()
                .size([h, w]);

        diagonal = d3.svg.diagonal()
                .projection(function(d) { return [d.y, d.x]; });

        svg = d3.select("body").append("svg:svg")
                .attr("width", w + m[1] + m[3])
                .attr("height", h + m[0] + m[2])
                .append("svg:g")
                .attr("transform", "translate(" + m[3] + "," + m[0] + ")");



        // Initialize the display to show a few nodes.
        //root.children.forEach(toggleAll);

        update(root);
    }

    function toggleAll(d) {
        if (d.children) {
            d.children.forEach(toggleAll);
            toggle(d);
        }
    }

    function update(source) {
        var duration = d3.event && d3.event.altKey ? 5000 : 500;

        // Compute the new tree layout.
        var nodes = tree.nodes(root).reverse();

        // Normalize for fixed-depth.
        nodes.forEach(function(d) { d.y = d.depth * 180; });

        // Update the nodes…
        var node = svg.selectAll("g.node")
                .data(nodes, function(d) { return d.id || (d.id = ++i); });

        // Enter any new nodes at the parent's previous position.
        var nodeEnter = node.enter().append("svg:g")
                .attr("class", "node")
                .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
                .on("click", function(d) { toggle(d); update(d); });

        nodeEnter.append("svg:circle")
                .attr("r", 1e-6)
                .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

	var nodeText = nodeEnter
                .append("svg:g")
                .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
                .attr("dy", ".35em")
                .style("font", "12px 'Helvetica Neue'");


	nodeText
            .append("svg:text")
            .attr("x", 10)
            .attr("y", 5)
            .text(function(d){return  d.name; });
        
        nodeText
            .append("svg:text")
            .text(function(d){return  d.title ; })
            .style("fill", "red")
            .attr("x", 10)
            .attr("y", 20);

        // Transition nodes to their new position.
        var nodeUpdate = node.transition()
                .duration(duration)
                .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

        nodeUpdate.select("circle")
                .attr("r", 4.5)
                .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

        nodeUpdate.select("text")
                .style("fill-opacity", 1);

        // Transition exiting nodes to the parent's new position.
        var nodeExit = node.exit().transition()
                .duration(duration)
                .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
                .remove();

        nodeExit.select("circle")
                .attr("r", 1e-6);

        nodeExit.select("text")
                .style("fill-opacity", 1e-6);

        // Update the links…
        var link = svg.selectAll("path.link")
                .data(tree.links(nodes), function(d) { return d.target.id; });

        // Enter any new links at the parent's previous position.
        link.enter().insert("svg:path", "g")
                .attr("class", "link")
                .attr("d", function(d) {
                    var o = {x: source.x0, y: source.y0};
                    return diagonal({source: o, target: o});
                })
                .transition()
                .duration(duration)
                .attr("d", diagonal);

        // Transition links to their new position.
        link.transition()
                .duration(duration)
                .attr("d", diagonal);

        // Transition exiting nodes to the parent's new position.
        link.exit().transition()
                .duration(duration)
                .attr("d", function(d) {
                    var o = {x: source.x, y: source.y};
                    return diagonal({source: o, target: o});
                })
                .remove();

        // Stash the old positions for transition.
        nodes.forEach(function(d) {
            d.x0 = d.x;
            d.y0 = d.y;
        });
    }

// Toggle children.
    function toggle(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
    }

    function decorate(d){
	return "[ "  + d.name + " ]" ;
    }

    return {
        init : init
    }

}(google, d3));

google.setOnLoadCallback(orgChart.init);
</script>
</head>
<body>
</body>
</html>
